package com.ellen.mac.chatdemo.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.im.v2.AVIMConversation;
import com.avos.avoscloud.im.v2.AVIMException;
import com.avos.avoscloud.im.v2.callback.AVIMConversationCreatedCallback;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.ellen.mac.chatdemo.R;
import com.ellen.mac.chatdemo.activity.ChatRoomAct;
import com.ellen.mac.chatdemo.adpter.MembersAdapter;
import com.ellen.mac.chatdemo.comment.BaseApp;
import com.ellen.mac.chatdemo.utils.ChatKit;
import com.ellen.mac.chatdemo.utils.LogUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * Created by aven on 17／12／2.
 * 所有人面
 */
public class AllUserFragment extends Fragment {

    protected SwipeRefreshLayout refreshLayout;
    protected RecyclerView recyclerView;

    private MembersAdapter itemAdapter;
    LinearLayoutManager layoutManager;
    List<AVUser> users;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.contact_fragment, container, false);
        refreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.contact_fragment_srl_list);
        recyclerView = (RecyclerView) view.findViewById(R.id.contact_fragment_rv_list);
        GridLayoutManager layoutManage = new GridLayoutManager(getActivity(), 1);
        recyclerView.setLayoutManager(layoutManage);
        users = new ArrayList<>();
        itemAdapter = new MembersAdapter(R.layout.userinfo_item, users);
        recyclerView.setAdapter(itemAdapter);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                findUser();
            }
        });
        recyclerView.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                joinChatRoom(users.get(position).getObjectId(),users.get(position).getUsername());
            }
        });
        return view;
    }
    private void joinChatRoom(final String objId,final String Name) {
        ChatKit.getInstance().getClient().createConversation(Arrays.asList(objId), Name+"&"+ChatKit.getInstance().getcurrentUserName(), null, false, true,
                new AVIMConversationCreatedCallback() {
                    @Override
                    public void done(AVIMConversation conversation, AVIMException e) {
                        if (e == null) {
                            Toast.makeText(getContext(), "Room Create Success id is " + conversation.getConversationId(), Toast.LENGTH_SHORT).show();
                            //todo 跳转到聊天室
                            Intent intent = new Intent(getContext(), ChatRoomAct.class);
                            intent.setPackage(getContext().getPackageName());
                            intent.setAction(BaseApp.CONVERSATION_ITEM_CLICK_ACTION);
                            intent.addCategory(Intent.CATEGORY_DEFAULT);
                            intent.putExtra(BaseApp.CONVERSATION_ID, conversation.getConversationId());
                            startActivity(intent);
                        }else{
                            LogUtils.logException(e);
                        }
                    }
                });

    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    @Override
    public void onResume() {
        super.onResume();
        refreshMembers();
    }

    private void refreshMembers() {
        itemAdapter.setNewData(users);
        itemAdapter.notifyDataSetChanged();
        refreshLayout.setRefreshing(false);
    }

    public void findUser() {
        new Thread() {
            public void run() {
                // tips:网络请求不能在主线程
                AVQuery<AVUser> userQuery = new AVQuery<>("_User");
                try {
                    users = userQuery.find();
                    Message msg = new Message();
                    Bundle data = new Bundle();
                    data.putString("userInfo", "ok");
                    msg.setData(data);
                    handler.sendMessage(msg);

                } catch (AVException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            if (data.getString("userInfo").equals("ok")) {
                refreshMembers();
            }
        }
    };


}
